#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#include <string.h>

typedef struct pessoa
{
	char nome[30];
	int idade;
	float renda;
} pessoa;

int main(int argc, char *argv[])
{
	int mpierr, rank, size, position, tambuf = 1024, i, tag = 16;
	MPI_Status status;
	char *message = (char *)malloc(tambuf*sizeof(char));
	pessoa p1;
	mpierr = MPI_Init(&argc, &argv);
	if(mpierr >= 0)
	{
		MPI_Comm_rank(MPI_COMM_WORLD, &rank);
		MPI_Comm_size(MPI_COMM_WORLD, &size);
		if(rank == 0)
		{
			strcpy(p1.nome, "Joao da Silva");
			p1.idade = 35;
			p1.renda = 1235.50;
			position = 0;
			MPI_Pack(&p1.idade, 1, MPI_INT, message, tambuf, &position, MPI_COMM_WORLD);
			MPI_Pack(p1.nome, 30, MPI_CHAR, message, tambuf, &position, MPI_COMM_WORLD);
			MPI_Pack(&p1.renda, 1, MPI_FLOAT, message, 100, &position, MPI_COMM_WORLD);
			for (i = 1; i < size; i++){
				MPI_Send(message, 100, MPI_PACKED, i, tag, MPI_COMM_WORLD);
			}
		}
		else
		{
			position = 0;
			MPI_Recv(message, tambuf, MPI_PACKED, 0, tag, MPI_COMM_WORLD, &status);
			MPI_Unpack(message, tambuf, &position, &p1.idade, 1, MPI_INT, MPI_COMM_WORLD);
			MPI_Unpack(message, tambuf, &position, p1.nome, 30, MPI_CHAR, MPI_COMM_WORLD);
			MPI_Unpack(message, tambuf, &position, &p1.renda, 1, MPI_FLOAT, MPI_COMM_WORLD);
			printf("Pessoa %s - Idade: %d - Renda: %8.2f\n\n\n", p1.nome, p1.idade, p1.renda);
			
		}
		MPI_Finalize();
	}
	
	return 0;
} 
